<?php
/**
 * Created by PhpStorm.
 * User: 沁塵
 * Date: 2019/4/20
 * Time: 19:57
 */

namespace app\api\controller\v1;

use app\api\model\Account;
use app\api\model\JdDistribute;
use app\api\model\JdEvent;
use app\api\model\ProductConfig;
use app\api\service\token\LoginToken;
use think\Db;
use think\Exception;
use think\Request;

class Jd
{
    public function addDis(Request $request)
    {
        $params = $request->post();
        $add = [];
        $add["video_url"] = $params["videoUrl"];
        $add["video_id"] = $params["video_id"];
        $add["cover"] = $params["cover"];
        $add["title"] = $params["title"];
//        todo
        $add["account_id"] = null;
        $add["jd_url"] = null;
        $add["topic"] = null;
        $add["tag"] = null;

        $account = Account::where("platform", "京东")->whereNull("remark")->where("bind_tb", $params["app_id"])->findOrEmpty();
        if (!$account->isEmpty()) {
            $add["account_id"] = $account["app_id"];
        }

        $product = ProductConfig::where("pid", $params["pid"])->whereNotNull("jd_url")->findOrEmpty();
        if (!$product->isEmpty()) {
            $add["jd_url"] = $product["jd_url"];
            $add["topic"] = $product["jd_topic"];
            $add["tag"] = $product["jd_tag"];
        }

        $res = JdDistribute::create($add);
        return writeJson(200, $res, '请求成功');

    }
    public function getAccountList()
    {
        $list = Account::field("id, account, password, app_id, name, cookie, category, platform, model_name, sound_model, num, get_time")
            ->where('platform','京东')->whereNotNull("cookie")->whereNull("remark")->select()->toArray();

        return writeJson(200,$list,'用户列表！');
    }

    public function getDistribute(Request $request)
    {
//        return writeJson(200, [], '成功');
        $params = $request->get();

        $all_accounts = [];
        $ok_accounts = Account::field('id')->whereNull('remark')
            ->where("id", ">=", $params["start"])
            ->where("id", "<=", $params["end"])
            ->select()->toArray();
        foreach ($ok_accounts as $ac) {
            $all_accounts[] = $ac["id"];
        }
//        $accounts = SnycDistribute::field("account_id,count(*) as count")
//            ->where("save_time", ">", date('Y-m-d 00:00:00'))
//            ->group("account_id")
//            ->having("count >= 75")
//            ->select()->toArray();
//
//        $used_account = [];
//        foreach ($accounts as $ac) {
//            $used_account[] = $ac["account_id"];
//        }

//        $array_diff = array_diff($all_accounts, $used_account);
//        5分钟内用过的不发
        $get_time = date("Y-m-d H:i:s", time() - 480);
        $get_time_account_id = JdDistribute::field("account_id")
            ->where("get_time",'>',$get_time)
            ->where("account_id", ">=", $params["start"])
            ->where("account_id", "<=", $params["end"])
            ->distinct(true)
            ->select()->toArray();

        $get_time_account = [];
        foreach ($get_time_account_id as $ac) {
            $get_time_account[] = $ac["account_id"];
        }

        $array_diff_diff = array_diff($all_accounts, $get_time_account);

//        剩余篇数为0的不发
        $full_account_id = Account::field("id")
            ->where("num", 0)
            ->where("get_time", ">", date("Y-m-d 00:00:00", time()))
            ->where("id", ">=", $params["start"])
            ->where("id", "<=", $params["end"])
            ->select()->toArray();

        $full_account = [];
        foreach ($full_account_id as $ac) {
            $full_account[] = $ac["id"];
        }

        $array_diff_diff_diff = array_diff($array_diff_diff, $full_account);
//        $rand_account_key = array_rand($array_diff_diff_diff);

        $yesterday = strtotime("-15 day");
        $yesterday15 = strtotime(date('Y-m-d 00:00:00', $yesterday));

        $query = JdDistribute::with("account")
            ->where('status',1)
//            ->where("account_id", ">",  35)
//            ->where("create_time", ">",  "2024-11-21 12:00:00")
//            ->where("valid_time", ">", date('Y-m-d H:i:s', $yesterday15))
            ->where("valid_time", ">", '2025-01-15 00:00:00')
            ->whereIn("account_id", $array_diff_diff_diff);

        if (isset($params["title"])) {
            $query = $query->whereLike("title", "%".$params["title"]."%");
        }
//        $sync = $query->fetchSql()->select();
//        dump($sync);die;
        $sync = $query->orderRand()->findOrEmpty();

        if($sync->isEmpty()){
            return writeJson(400, [], '暂无分发数据');
        }
        JdDistribute::where('id',$sync['id'])->update(['status'=>'2', 'get_time'=>Date("y-m-d H:i:s")]);

        return writeJson(200, $sync, '获取成功');
    }

    public function updateDistribute(Request $request)
    {
        $params = $request->post();
        $update = [
            'status' => $params['status'],
            'nid' => empty($params['nid']) ? null : $params['nid'],
            'reason' => empty($params['reason']) ? null : $params['reason']
        ];
        if ($params["status"] == 3) {
            $update["save_time"] = date('Y-m-d H:i:s',time());
        }
        if ($params["status"] == 5) {
            $update["pub_time"] = date('Y-m-d H:i:s',time());
        }

        if ($params["status"] == 4 and ($params["reason"] == 'cookie过期' or $params["reason"] == '发满了')) {
            $update["status"] = 1;
        }

        $res = JdDistribute::where('id',$params['id'])->update($update);

        if ($params["reason"] == "cookie过期") {
            Account::where("id", $params["account_id"])->update(["remark"=>"cookie过期"]);
        }

        return writeJson(200, $res, '更新成功');
    }

    public function backfillDistribute(Request $request)
    {
        $params = $request->post();

        $info = JdDistribute::where("id", $params["id"])->save($params);
        return writeJson(200, $info, '成功！');
    }

    public function list(Request $request)
    {
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();

        $pageSize = $params['pageSize'] ?? 50;
        $dis = new JdDistribute();

        $query = $dis->field("title, jd_url, price, rate, mission, account_id, status, reason")
            ->alias('a')
            ->join('account b', 'a.account_id=b.app_id');

        if ($uid != 1) {
            $query = $query->where("uid", $uid);
        }
        if (!empty($params["status"])) {
            $query = $query->where("status", $params["status"]);
        }
        if (!empty($params["start_time"])) {
            $query = $query->where("create_time", ">", $params["start_time"]);
        }

        $list = $query->order("id desc")->paginate($pageSize);
        return writeJson(200,$list,'数据列表！');
    }




    // 弃用
    public function addEvent(Request $request)
    {
        $params = $request->post();
        $event = new JdEvent();
        $uid = LoginToken::getInstance()->getCurrentUid();
        if (!empty($uid)) {
            $params["uid"] = $uid["id"];
        }
        $event->create($params);

        return writeJson(200, '', '请求成功');

    }

    // 弃用
    public function getEvent(Request $request)
    {
        $params = $request->get();

        $event = new JdEvent();
        $info = $event->with("ac")->where("status", 1)->findOrEmpty();
        if (!$info->isEmpty()) {
            $info->status = 2;
            $info->save();
        }
        return writeJson(200,$info,'完成！');

    }

    // 弃用
    public function backfillEvent(Request $request)
    {
        $params = $request->post();

        $info = JdEvent::where("id", $params["id"])->update($params);
        return writeJson(200, $info, '成功！');
    }

    // 弃用
    public function addDistribute(Request $request)
    {
        $params = $request->post();
        $event = new JdEvent();
        $dis = new JdDistribute();
        DB::startTrans();
        try {
            // 更新event
            if (!empty($params["id"])) {
                $event->where("id", $params["id"])->update(["status"=>3]);
            }
            $count = $dis->where("gather_id", $params['id'])->count();
            if ($count == 0) {
                $params["gather_id"] =  $params['id'];
                $params["uid"] =  $params['uid'];
                unset($params["id"]);
                $dis->create($params);
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,false,'失败！');
        }

        return writeJson(200, '', '请求成功');

    }

    // 弃用
    public function eventList(Request $request)
    {
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();

        $pageSize = $params['pageSize'] ?? 50;
        $event = new JdEvent();

        $query = $event->field("title, jd_url, price, rate, mission, account, status, reason")
            ->alias('a')
            ->join('account b', 'a.account=b.app_id');

        if ($uid != 1) {
            $query = $query->where("uid", $uid);
        }
        if (!empty($params["status"])) {
            $query = $query->where("status", $params["status"]);
        }
        if (!empty($params["start_time"])) {
            $query = $query->where("create_time", ">", $params["start_time"]);
        }

        $list = $query->order("id desc")->paginate($pageSize);
        return writeJson(200,$list,'数据列表！');
    }




}